package top.zhdev.community.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import top.zhdev.community.entity.LoginTicket;
import top.zhdev.community.entity.User;
import top.zhdev.community.mapper.UserMapper;
import top.zhdev.community.service.UserService;
import top.zhdev.community.utils.CommunityConstant;
import top.zhdev.community.utils.CommunityUtil;
import top.zhdev.community.utils.MailClient;
import top.zhdev.community.utils.RedisKeyUtil;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 登录业务处理
 */
@Service
public class UserServiceImpl implements UserService, CommunityConstant {

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    private UserMapper userMapper;
    private MailClient mailClient;

    @Autowired
    public void setUserMapper(UserMapper userMapper){
        this.userMapper = userMapper;
    }

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private TemplateEngine templateEngine;

    @Autowired
    public void setMailClient(MailClient mailClient){
        this.mailClient = mailClient;
    }

    /**
     * 登录处理
     * @param username
     * @param password
     * @param expiredSeconds
     * @return
     */
    @Override
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String,Object> map = new HashMap<>();

        // 空值处理
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","账号不能为空");
            return map;
        }

        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空");
            return map;
        }

        // 验证账号
        User user = userMapper.getUserByName(username);
        if(user == null){
            map.put("usernameMsg","该账号不存在");
            return map;
        }

        // 验证状态
        if(user.getStatus() == 0){
            map.put("usernameMsg","该账号未激活");
            return map;
        }

        // 验证密码(密码加上加密盐后，转化成md5)
        password = CommunityUtil.md5(password+user.getSalt());
        if(!user.getPassword().equals(password)){
            map.put("passwordMsg","密码不正确");
            return map;
        }

        // 生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));

        String ticketKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(ticketKey,loginTicket);

        map.put("ticket",loginTicket.getTicket());
        return map;
    }

    /**
     * 根据userId获取用户信息
     * @param userId
     * @return
     */
    @Override
    public User getUserById(Integer userId) {
        User user = getCache(userId);
        if(user == null){
            user = initCache(userId);
        }
        return user;
    }

    /**
     * 获取登录凭证
     * @param ticket
     * @return
     */
    @Override
    public LoginTicket getLoginTicket(String ticket) {
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
    }

    /**
     * 根据用户类型，获取相应的权限
     * @param userId
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(Integer userId) {
        User user = userMapper.getUserById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch(user.getType()){
                    case 1: return AUTHORITY_ADMIN;
                    case 2: return AUTHORITY_MODERATOR;
                    default: return AUTHORITY_USER;
                }
            }
        });
        return list;
    }

    /**
     * 退出登录
     * @param ticket
     */
    @Override
    public void logout(String ticket) {
        // 是否可以进行优化
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicke = (LoginTicket) redisTemplate.opsForValue().get(ticketKey);
        loginTicke.setStatus(1);
        redisTemplate.opsForValue().set(ticketKey,loginTicke);
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> register(User user) {
        Map<String,Object> map = new HashMap<>();
        // 空值处理
        if(user == null){
            throw new IllegalArgumentException("参数不能为空");
        }

        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","用户名不能为空");
            return map;
        }

        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg","密码不能为空");
            return map;
        }

        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg","邮箱不能为空");
            return map;
        }

        // 验证账号
        User registerUser = userMapper.getUserByName(user.getUsername());
        if(registerUser != null){
            map.put("usernameMsg","该账号昵称已存在");
            return map;
        }

        // 验证邮箱
        registerUser = userMapper.getUserByEmail(user.getEmail());
        if(registerUser != null){
            map.put("emailMsg","邮箱已被注册");
            return map;
        }

        // 注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        int result = userMapper.saveUser(user);

        //激活邮件
        Context context = new Context();
        context.setVariable("email",user.getEmail());
        // 生成激活连接，用户点击连接后，将向服务器发送给请求
        // http://localhost:8080/community/activation/101/code
        String url = domain + contextPath + "/activation" + "/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation",context);
        mailClient.sendMail(user.getEmail(),"激活账号",content);
        return map;
    }

    /**
     * 激活用户（这里包含判断是否重复激活，即多次点击激活连接的行为）
     * @param userId
     * @param code
     * @return
     */
    @Override
    public int activation(int userId, String code) {
        User user = userMapper.getUserById(userId);
        if(user.getStatus() == 1){
            return ACTIVATION_REPEAT;
        }else if(user.getActivationCode().equals(code)){
            // 更改状态，变为已激活
            userMapper.updateStatus(userId,1);
            // 清楚redis中的缓存数据（何时存入的？？？）
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        }else {
            return ACTIVATION_FAILURE;
        }
    }

    /**
     * 查询指定用户的帖子数量
     * @param userId
     * @return
     */
    @Override
    public int getDiscussPostsByUserId(int userId) {
        return userMapper.getDiscussPostsByUserId(userId);
    }

    /**
     * 更新用户头像
     * @param id
     * @param url
     */
    @Override
    public int updateHeaderUrl(Integer id, String url) {
        // 先去更新，再去清理缓存。可以避免更新数据库失败，缓存消失的现象。
        int rows = userMapper.updateHeader(id,url);
        clearCache(id);
        return rows;
    }

    /**
     * 通过昵称查找用户
     * @param username
     * @return
     */
    @Override
    public User getUserByName(String username) {
        return userMapper.getUserByName(username);
    }

    /**
     * 更新用户信息，清除缓存数据
     * @param userId
     */
    private void clearCache(int userId) {
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(userKey);
    }


    /**
     * 根据userId从redis缓存中获取用户信息
     * @param userId
     * @return
     */
    public User getCache(int userId){
        String userKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(userKey);
    }

    /**
     * 根据userId从数据库中查询用户信息，然后在放入Redis缓存中
     * @param userId
     * @return
     */
    public User initCache(int userId){
        User user = userMapper.getUserById(userId);
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(userKey,user,3600, TimeUnit.SECONDS);
        return user;
    }
}
